package com.dongpl.config.shiro;

import com.dongpl.module.sysUser.entity.SysPerms;
import com.dongpl.module.sysUser.entity.SysUser;
import com.dongpl.module.sysUser.service.SysUserService;
import com.dongpl.utils.ApplicationContextUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;

import java.util.List;

/**
 * 自定义Realm
 * @author Administrator
 */
public class CustomerRealm extends AuthorizingRealm {

    /**
     * 授权(验证权限时调用)
     * 获取用户权限集合
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser principal = (SysUser) principalCollection.getPrimaryPrincipal();
        //获取UserService对象
        SysUserService userService = (SysUserService) ApplicationContextUtil.getBean("sysUserServiceImpl");
        SysUser user = userService.findRoleByUsername(principal.getUsername());
        //基于角色授权
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role ->{
                info.addRole(role.getName());
                //权限信息
                List<SysPerms> perms = userService.findPermsByRoleId2(role.getId());
                if(!CollectionUtils.isEmpty(perms) && perms.get(0)!=null ){
                    perms.forEach(perm-> info.addStringPermission(perm.getName()));
                }
            });
            return info;
        }
        return null;
    }

    /**
     * 认证(登录时调用)
     * 验证用户登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        //获取UserService对象
        SysUserService userService = (SysUserService) ApplicationContextUtil.getBean("sysUserServiceImpl");
        SysUser user = userService.findByUsername(principal);
        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), new MyByteSource(user.getSalt()), this.getName());
    }

}